package com.haoyun.mirage.user.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.haoyun.common.core.BaseException;
import com.haoyun.mirage.user.mapper.SysDictMapper;
import com.haoyun.mirage.user.model.entity.SysDict;
import com.haoyun.mirage.user.service.ISysDictService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xiaoleilu.hutool.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yanhao
 * @since 2018-07-02
 */
@Service
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements ISysDictService {

    @Autowired
    SysDictMapper sysDictMapper;


    @Override
    @Transactional
    public Boolean deleteDict(Long id) {
        //判断是根节点 或者子节点 (删除该id,以及parentId下子节点)
        this.deleteById(id);
        //删除子节点
        return this.delete(new EntityWrapper<SysDict>().eq("parent_id", id));
    }

    @Override
    @Transactional
    public Boolean insertDict(SysDict sysDict) throws BaseException{
        if (this.isExist(sysDict.getKeyworld())){
            throw new BaseException("关键字 ["+ sysDict.getKeyworld()+"] 已存在！");
        }
        return this.insert(sysDict);
    }

    @Override
    @Transactional
    public Boolean updateDictById(SysDict sysDict) {
        Assert.notNull(sysDict.getId(), "数据字典id不能为空！");
        return this.updateById(sysDict);
    }

    @Override
    public SysDict getDictById(Long id) {
        return sysDictMapper.selectById(id);
    }

    private boolean isExist(String keyworld) {
        SysDict sysDict = this.selectOne(new EntityWrapper<SysDict>().eq("keyworld", keyworld));
        if (sysDict == null) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
}
